import os
from Util.SQL import *
from Util.Return import *
from Util.Process import *
from Data.DataStorage import *
from PIL import Image
import shutil


###########################
# 数据运维:处理各种数据异常问题
###########################


def make_landsat_quicklook():
    hdfs_available_path = "/" + get_config("data", "Landsat")['available_path']
    hdfs_quicklook_path = "/" + get_config("data", "Landsat")['quicklook_path']
    local_available_path = get_path(os.path.abspath(__file__), 2, get_config("data", "Landsat")['available_path'])
    local_quicklook_path = get_path(os.path.abspath(__file__), 2, get_config("data", "Landsat")['quicklook_path'])
    hdfs = HDFS()
    scenes = select("select * from data where dataset = 'Landsat' and available = 1")
    for scene in scenes:
        flag, type = hdfs.exist(hdfs_quicklook_path + "/" + scene["scene_id"] + ".png")
        if flag is False:
            hdfs.pull(hdfs_available_path + "/" + scene["scene_id"] + ".TIFF", local_available_path)
            # 缩略图处理开始
            image = Image.open(os.path.join(local_available_path, scene["scene_id"] + '.TIFF'))
            image = image.resize((1024, 1024))  # 调整图像大小为缩略图尺寸
            image.save(os.path.join(local_quicklook_path, scene["scene_id"] + '.png'), "PNG")  # 将图像保存为PNG格式
            # 缩略图处理结束
            hdfs.push(hdfs_quicklook_path, os.path.join(local_quicklook_path, scene["scene_id"] + '.png'))
            os.remove(os.path.join(local_available_path, scene["scene_id"] + '.TIFF'))
            INFO("INFO", f"{scene['scene_id']} Success make_landsat_quicklook!")
        else:
            INFO("INFO", f"{scene['scene_id']} have quicklook, skip this scene!")


def empty_temp_path():
    data_list = get_config("config", "data_manage")["data_list"]
    for dataset in data_list:
        data_path = [get_path(os.path.abspath(__file__), 2, get_config("data", dataset)['download_path']),
                     get_path(os.path.abspath(__file__), 2, get_config("data", dataset)['available_path'])]
        for directory in data_path:
            for file in os.listdir(directory):
                file_path = os.path.join(directory, file)
                if os.path.isfile(file_path):
                    os.remove(file_path)
                else:
                    shutil.rmtree(file_path)

            INFO("INFO", f"Empty temp path {directory}!")


def synchronize_quicklook():
    data_list = get_config("config", "data_manage")["data_list"]
    hdfs = HDFS()
    for dataset in data_list:
        hdfs_quicklook_path = "/" + get_config("data", dataset)['quicklook_path']
        local_quicklook_path = get_path(os.path.abspath(__file__), 2, get_config("data", dataset)['quicklook_path'])
        hdfs.pull(hdfs_quicklook_path, local_quicklook_path)


# make_landsat_quicklook()      # 补全缩略图
synchronize_quicklook()     # 同步缩略图
